<template>
  <div>
    <div class="statistics-layout">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card shadow="hover" class="data-card">
            <div class="data-card-title">物资总数</div>
            <div class="data-card-value">{{ stats.物资Count }}</div>
            <div class="data-card-footer">
              <div class="data-card-trend">
                <i class="el-icon-top" style="color: #67C23A;"></i>
                <span>{{ stats.物资Increase }}%</span>
              </div>
              <div class="data-card-desc">较上月</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="data-card">
            <div class="data-card-title">设备总数</div>
            <div class="data-card-value">{{ stats.设备Count }}</div>
            <div class="data-card-footer">
              <div class="data-card-trend">
                <i class="el-icon-top" style="color: #67C23A;"></i>
                <span>{{ stats.设备Increase }}%</span>
              </div>
              <div class="data-card-desc">较上月</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="data-card">
            <div class="data-card-title">调拨总数</div>
            <div class="data-card-value">{{ stats.transferCount }}</div>
            <div class="data-card-footer">
              <div class="data-card-trend">
                <i class="el-icon-top" style="color: #67C23A;"></i>
                <span>{{ stats.transferIncrease }}%</span>
              </div>
              <div class="data-card-desc">较上月</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="data-card">
            <div class="data-card-title">收藏总数</div>
            <div class="data-card-value">{{ stats.favoriteCount }}</div>
            <div class="data-card-footer">
              <div class="data-card-trend">
                <i class="el-icon-top" style="color: #67C23A;"></i>
                <span>{{ stats.favoriteIncrease }}%</span>
              </div>
              <div class="data-card-desc">较上月</div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" style="margin-top: 20px;">
        <el-col :span="12">
          <el-card shadow="never">
            <div slot="header" class="chart-header">
              <span>物资/设备分类统计</span>
              <el-radio-group v-model="categoryChartType" size="mini" @change="loadCategoryData">
                <el-radio-button label="物资">物资</el-radio-button>
                <el-radio-button label="设备">设备</el-radio-button>
              </el-radio-group>
            </div>
            <div class="chart-container">
              <div ref="categoryChart" style="width: 100%; height: 350px;"></div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card shadow="never">
            <div slot="header" class="chart-header">
              <span>物资/设备地区分布</span>
              <el-radio-group v-model="regionChartType" size="mini" @change="loadRegionData">
                <el-radio-button label="物资">物资</el-radio-button>
                <el-radio-button label="设备">设备</el-radio-button>
                <el-radio-button label="all">全部</el-radio-button>
              </el-radio-group>
            </div>
            <div class="chart-container">
              <div ref="regionChart" style="width: 100%; height: 350px;"></div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" style="margin-top: 20px;">
        <el-col :span="12">
          <el-card shadow="never">
            <div slot="header" class="chart-header">
              <span>调拨申请趋势</span>
              <el-select v-model="transferTimeRange" size="mini" @change="loadTransferTrend">
                <el-option label="最近7天" value="7"></el-option>
                <el-option label="最近30天" value="30"></el-option>
                <el-option label="最近90天" value="90"></el-option>
              </el-select>
            </div>
            <div class="chart-container">
              <div ref="transferChart" style="width: 100%; height: 350px;"></div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card shadow="never">
            <div slot="header" class="chart-header">
              <span>热门物资/设备排行</span>
              <el-select v-model="hotItemsLimit" size="mini" @change="loadHotItems">
                <el-option label="Top 5" value="5"></el-option>
                <el-option label="Top 10" value="10"></el-option>
                <el-option label="Top 20" value="20"></el-option>
              </el-select>
            </div>
            <div class="chart-container">
              <div ref="hotItemsChart" style="width: 100%; height: 350px;"></div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" style="margin-top: 20px;">
        <el-col :span="24">
          <el-card shadow="never">
            <div slot="header" class="chart-header">
              <span>物资/设备状态统计</span>
            </div>
            <div class="chart-container">
              <div ref="statusChart" style="width: 100%; height: 350px;"></div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import { http } from "@/api";
import * as echarts from 'echarts';

export default {
  name: "IdleStatistics",
  data() {
    return {
      stats: {
        物资Count: 0,
        物资Increase: 0,
        设备Count: 0,
        设备Increase: 0,
        transferCount: 0,
        transferIncrease: 0,
        favoriteCount: 0,
        favoriteIncrease: 0
      },

      // 图表相关
      categoryChartType: '物资',
      regionChartType: 'all',
      transferTimeRange: '30',
      hotItemsLimit: '10',

      // 图表实例
      categoryChart: null,
      regionChart: null,
      transferChart: null,
      hotItemsChart: null,
      statusChart: null
    };
  },
  mounted() {
    this.fetchStatistics();
    this.initCharts();

    // 监听窗口大小变化，重绘图表
    window.addEventListener('resize', this.resizeCharts);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeCharts);

    // 销毁图表实例
    if (this.categoryChart) this.categoryChart.dispose();
    if (this.regionChart) this.regionChart.dispose();
    if (this.transferChart) this.transferChart.dispose();
    if (this.hotItemsChart) this.hotItemsChart.dispose();
    if (this.statusChart) this.statusChart.dispose();
  },
  methods: {
    fetchStatistics() {
      http.idleItem.statistics().then(res => {
        this.stats = res.data;
      });
    },

    initCharts() {
      // 初始化各个图表
      this.categoryChart = echarts.init(this.$refs.categoryChart);
      this.regionChart = echarts.init(this.$refs.regionChart);
      this.transferChart = echarts.init(this.$refs.transferChart);
      this.hotItemsChart = echarts.init(this.$refs.hotItemsChart);
      this.statusChart = echarts.init(this.$refs.statusChart);

      // 加载各个图表数据
      this.loadCategoryData();
      this.loadRegionData();
      this.loadTransferTrend();
      this.loadHotItems();
      this.loadStatusData();
    },

    resizeCharts() {
      if (this.categoryChart) this.categoryChart.resize();
      if (this.regionChart) this.regionChart.resize();
      if (this.transferChart) this.transferChart.resize();
      if (this.hotItemsChart) this.hotItemsChart.resize();
      if (this.statusChart) this.statusChart.resize();
    },

    loadCategoryData() {
      http.idleItem.categoryStatistics({ type: this.categoryChartType }).then(res => {
        const data = res.data;
        const option = {
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
          },
          legend: {
            orient: 'vertical',
            right: 10,
            top: 'center',
            data: data.map(item => item.name)
          },
          series: [
            {
              name: this.categoryChartType === '物资' ? '物资分类' : '设备分类',
              type: 'pie',
              radius: ['50%', '70%'],
              avoidLabelOverlap: false,
              label: {
                show: false,
                position: 'center'
              },
              emphasis: {
                label: {
                  show: true,
                  fontSize: '16',
                  fontWeight: 'bold'
                }
              },
              labelLine: {
                show: false
              },
              data: data.map(item => ({
                value: item.count,
                name: item.name
              }))
            }
          ]
        };
        this.categoryChart.setOption(option);
      });
    },

    loadRegionData() {
      http.idleItem.regionStatistics({ type: this.regionChartType }).then(res => {
        const data = res.data;
        const option = {
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
          },
          legend: {
            type: 'scroll',
            orient: 'vertical',
            right: 10,
            top: 'center',
            data: data.map(item => item.name)
          },
          series: [
            {
              name: '地区分布',
              type: 'pie',
              radius: '55%',
              center: ['40%', '50%'],
              data: data.map(item => ({
                value: item.count,
                name: item.name
              })),
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ]
        };
        this.regionChart.setOption(option);
      });
    },

    loadTransferTrend() {
      http.idleTransfer.trend({ days: this.transferTimeRange }).then(res => {
        const data = res.data;
        const option = {
          tooltip: {
            trigger: 'axis'
          },
          legend: {
            data: ['申请数', '批准数', '完成数']
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            boundaryGap: false,
            data: data.dates
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              name: '申请数',
              type: 'line',
              stack: '总量',
              data: data.apply
            },
            {
              name: '批准数',
              type: 'line',
              stack: '总量',
              data: data.approve
            },
            {
              name: '完成数',
              type: 'line',
              stack: '总量',
              data: data.complete
            }
          ]
        };
        this.transferChart.setOption(option);
      });
    },

    loadHotItems() {
      http.idleItem.hotItems({ limit: this.hotItemsLimit }).then(res => {
        const data = res.data;
        const option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'value',
            boundaryGap: [0, 0.01]
          },
          yAxis: {
            type: 'category',
            data: data.map(item => item.name),
            inverse: true
          },
          series: [
            {
              name: '浏览次数',
              type: 'bar',
              data: data.map(item => item.view_count),
              itemStyle: {
                color: function(params) {
                  const colorList = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'];
                  return colorList[params.dataIndex % colorList.length];
                }
              }
            }
          ]
        };
        this.hotItemsChart.setOption(option);
      });
    },

    loadStatusData() {
      http.idleItem.statusStatistics().then(res => {
        const data = res.data;
        const option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          legend: {
            data: ['物资', '设备']
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: ['可用', '已预订', '已调拨', '已报废']
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              name: '物资',
              type: 'bar',
              data: [
                data.物资.available,
                data.物资.reserved,
                data.物资.transferred,
                data.物资.scrapped
              ]
            },
            {
              name: '设备',
              type: 'bar',
              data: [
                data.设备.available,
                data.设备.reserved,
                data.设备.transferred,
                data.设备.scrapped
              ]
            }
          ]
        };
        this.statusChart.setOption(option);
      });
    }
  }
};
</script>

<style scoped>
.statistics-layout {
  margin-top: 20px;
}
.data-card {
  height: 120px;
  position: relative;
}
.data-card-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 10px;
}
.data-card-value {
  font-size: 30px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 15px;
}
.data-card-footer {
  display: flex;
  align-items: center;
  font-size: 12px;
}
.data-card-trend {
  display: flex;
  align-items: center;
  margin-right: 10px;
}
.data-card-desc {
  color: #909399;
}
.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.chart-container {
  position: relative;
}
</style>
